package com.cvmars.jianyou.module.activity;

import android.app.ActivityOptions;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.cvmars.jianyou.R;
import com.cvmars.jianyou.api.api.Api;
import com.cvmars.jianyou.api.api.HttpUtils;
import com.cvmars.jianyou.api.api.SimpleSubscriber;
import com.cvmars.jianyou.api.model.HttpResult;
import com.cvmars.jianyou.api.model.UserMode;
import com.cvmars.jianyou.config.UserOp;
import com.cvmars.jianyou.model.UserInfoManager;
import com.cvmars.jianyou.model.UserModel;
import com.cvmars.jianyou.module.adapter.HomeFindAdapter;
import com.cvmars.jianyou.module.base.BaseActivity;
import com.cvmars.jianyou.module.model.FindListModel;
import com.cvmars.jianyou.module.model.FindModel;
import com.cvmars.jianyou.ui.pulltorefresh.PulltoRefreshRecyclerView;
import com.cvmars.jianyou.utils.ImageUtils;
import com.cvmars.jianyou.utils.ToastUtils;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.rong.imkit.RongIM;
import jp.wasabeef.glide.transformations.BlurTransformation;


public class PersonHomeActivity extends BaseActivity {

    @BindView(R.id.list_home)
    PulltoRefreshRecyclerView listHome;

    String userid;

    ImageView ivBg, ivAvator, iv_Sex, love;

    TextView txtname, txtIntro, txtEmpty, txtGuanzhuss, txtFans, txt_address;

    HomeFindAdapter homeAdapter;

    List<FindModel> modelList = new ArrayList<>();
    @BindView(R.id.rl_chat)
    RelativeLayout rlChat;
    @BindView(R.id.txt_guanzhu)
    TextView txtGuanzhu;
    @BindView(R.id.rl_guanzhu)
    RelativeLayout rlGuanzhu;
    @BindView(R.id.ll_chat)
    LinearLayout llChat;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_person_home);
        ButterKnife.bind(this);
        userid = getIntent().getStringExtra("userid");
        QMUIStatusBarHelper.translucent(this);
        if (!UserInfoManager.getInstance().isOneSelf(userid)) {

            llChat.setVisibility(View.VISIBLE);
        }

        homeAdapter = new HomeFindAdapter(this, R.layout.item_find_home, modelList);
        listHome.setAdapter(homeAdapter);
        View headerView = LayoutInflater.from(this).inflate(R.layout.header_home_person, null);
        ivBg = headerView.findViewById(R.id.iv_person_bg);
        ivAvator = headerView.findViewById(R.id.iv_person_avator);
        txtname = headerView.findViewById(R.id.txt_usernmae);
        iv_Sex = headerView.findViewById(R.id.iv_Sex);
        txtIntro = headerView.findViewById(R.id.txt_intro);
        txtEmpty = headerView.findViewById(R.id.txt_empty);
        txtGuanzhuss = headerView.findViewById(R.id.txt_guanzhu);
        txtFans = headerView.findViewById(R.id.txt_fans);
        txt_address = headerView.findViewById(R.id.txt_address);
        love = headerView.findViewById(R.id.love);

        requestDataFind();
        homeAdapter.addHeaderView(headerView);
        listHome.setPullRefreshListener(new PulltoRefreshRecyclerView.RecyPtrHandler() {
            @Override
            public void onLoadMore() {
                requestDataFind();
            }

            @Override
            public void onRefresh() {
                listHome.mCurPager++;
                requestDataFind();
            }
        });
        listHome.loadMoreEnd();


        homeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(PersonHomeActivity.this, FindDetailActivity.class);

                FindModel findModel = modelList.get(position);
                findModel.customer = mUserModel;
                intent.putExtra("data", findModel);
//                getActivity().startActivity(intent);

                    startActivity(intent);
            }
        });


        requestData();
    }


    private void requestDataFind() {


        HttpUtils.getInstance().toSubscribe(Api.getInstance().getPersonFindList(userid, listHome.mCurPager)
                , new SimpleSubscriber<HttpResult<FindListModel>>() {
                    @Override
                    protected void _onNext(HttpResult<FindListModel> o) {

                        getLoadDialogAndDismiss();

                        FindListModel data = o.getData();

                        if (data != null) {

                            List<FindModel> results = data.results;


                            listHome.refreshComplete();
                            listHome.loadMoreComplete();
                            if (results != null) {

                                if (listHome.mCurPager == 1) {
                                    modelList.clear();
                                }
                                modelList.addAll(results);
                                homeAdapter.notifyDataSetChanged();
                                txtEmpty.setVisibility(modelList.size() == 0 ? View.VISIBLE : View.GONE);
                            }

                            if (data.next == null) {
                                listHome.loadMoreEnd();
                            }
                        }
                    }

                    @Override
                    protected void _onError(String message) {

                    }
                });
    }


    UserModel mUserModel;

    private void requestData() {

        getLoadDialogAndShow();
        HttpUtils.getInstance().toSubscribe(Api.getInstance().getUserInfo(userid)
                , new SimpleSubscriber<HttpResult<UserModel>>() {
                    @Override
                    protected void _onNext(HttpResult<UserModel> o) {
                        UserModel data = o.getData();
                        mUserModel = data;
                        getLoadDialogAndDismiss();
                        if (data != null) {
                            ImageUtils.loadImage(PersonHomeActivity.this, data.avatar_url, ivAvator);

                            Glide.with(PersonHomeActivity.this).load(data.avatar_url)
                                    .bitmapTransform(new BlurTransformation(PersonHomeActivity.this, 24))
                                    .diskCacheStrategy(DiskCacheStrategy.SOURCE).into(ivBg);
                            txtIntro.setText(!TextUtils.isEmpty(data.intro) ? data.intro : data.address_company);
                            txtname.setText(data.name);
                            txt_address.setText("@" + data.address_home);
                            homeAdapter.notifyDataSetChanged();
                            txtGuanzhuss.setText("关注：" + data.following_count);
                            txtFans.setText("粉丝：" + data.followers_count);
                            iv_Sex.setImageResource(data.gender == 1 ? R.drawable.ic_male : R.drawable.ic_women);

                            love.setVisibility(data.is_rut ? View.VISIBLE : View.GONE);
                            if (data.relation_status == 1) {

                                txtGuanzhu.setText("已关注");

                            } else if (data.relation_status == 2) {

                                txtGuanzhu.setText("互相关注");
                            } else {

                                txtGuanzhu.setText("加关注");
                            }
                        }
                    }

                    @Override
                    protected void _onError(String message) {

                    }
                });
    }

    @OnClick({R.id.rl_chat, R.id.rl_guanzhu})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_chat:

                if (mUserModel != null) {
                    String userId = mUserModel.id;
                    String name = mUserModel.name;

                    if (mUserModel.relation_status == 2 || (mUserModel.is_rut && UserInfoManager.is_rut)) {

                        RongIM.getInstance().startPrivateChat(this, userId, name);
                    } else {
                        ToastUtils.show("互相关注才能聊天");
                    }
                }

                break;
            case R.id.rl_guanzhu:

                if (mUserModel.relation_status == -1) {

                    onFollow(mUserModel, "1");
                } else {
                    onUnFollow(mUserModel);
                }
                break;
        }
    }


    private void onUnFollow(final UserModel customid) {

        HttpUtils.getInstance().toSubscribe(Api.getInstance().deleteUserFollow(
                customid.id)
                , new SimpleSubscriber<HttpResult<UserMode>>() {
                    @Override
                    protected void _onNext(HttpResult<UserMode> o) {

                        ToastUtils.show("取消关注成功");
                        customid.relation_status = -1;
                        txtGuanzhu.setText("加关注");
                    }

                    @Override
                    protected void _onError(String message) {

                    }
                });
    }


    private void onFollow(final UserModel model, final String status) {

        HttpUtils.getInstance().toSubscribe(Api.getInstance().postUserFollow(
                model.id, status)
                , new SimpleSubscriber<HttpResult<UserMode>>() {
                    @Override
                    protected void _onNext(HttpResult<UserMode> o) {

                        ToastUtils.show("关注成功");
                        model.relation_status = 1;
                        txtGuanzhu.setText("已关注");
                    }

                    @Override
                    protected void _onError(String message) {

                    }
                });
    }

}
